package fun.diaoer.config.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSON;

import fun.diaoer.common.Contants;
import fun.diaoer.common.JsonResult;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class DiaoerLogoutSuccessHandler implements LogoutSuccessHandler {

	@Override
	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		Assert.notNull(request, "HttpServletRequest required");
         HttpSession session = request.getSession(false);
         if (session != null) {
              session.invalidate(); //使当前会话失效
         }
	     SecurityContextHolder.clearContext(); //清空安全上下文
		
		log.error("登出成功");
		JsonResult<String> jr=new JsonResult<>();
		jr.setCode(200);
		Contants.buildLoginResponse(request, response);
		jr.setMsg("登出成功");
		response.getWriter().write(JSON.toJSONString(jr));
	}

}
